//取值
function get(key, sync = true) {
  try {
    if (sync) {
      return uni.getStorageSync(key);
    } else {
      let data = '';
      uni.getStorage({
        key: key,
        success: function (res) {
          data = res.data;
        }
      });
      return data;
    }
  } catch (e) {
    return false;
  }
}

//赋值
function set(key, value, sync = true) {
  // console.log("全局-------------->set: " + JSON.stringify(value));
  try {
    if (sync) {
      return uni.setStorageSync(key, value);
    } else {
      uni.setStorage({
        key: key,
        data: value
      });
    }
  } catch (e) {
    console.log("全局缓存set()-->e: " + JSON.stringify(e));
  }
}

//移除
function del(key, sync = true) {
  try {
    if (sync) {
      return uni.removeStorageSync(key);
    } else {
      uni.removeStorage({
        key: key
      });
    }
  } catch (e) {
    return false;
  }
}

//清空
function clear(sync = true) {
  try {
    if (sync) {
      return uni.clearStorageSync();
    } else {
      uni.clearStorage();
    }
  } catch (e) {
    return false;
  }
}

// 设置缓存，带有效期
function setByExpire(key, value, seconds) {
  let timestamp = Math.round(Date.now() / 1000)
  let expire
  if (!seconds || seconds == 0) {
    expire = timestamp + 7200
  }
  value = value + "|" + expire
  set(key, value)
}

// 获取缓存
function getByExpire(key) {
  let timestamp = Math.round(Date.now() / 1000)
  let value = get(key)
  if (value) {
    var tmp = value.split("|")
    if (!tmp[1] || timestamp >= tmp[1]) {
      del(key)
      return ""
    } else {
      return tmp[0]
    }
  }
}


export default {
  get,
  set,
  del,
  clear,
  setByExpire,
  getByExpire,
}
